# coding:utf-8
__author__ = '啦拉嘿'
__date__ = '2020/3/11 16:38'
import os, django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_orm.settings")  # project_name 项目名称
django.setup()
import tkinter as tk
import datetime
import tkinter.messagebox as messagebox
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from tkinter import ttk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from cycler import cycler
import random

from connect_db.models import UseTime, User, Category
from connect_db.views import time_frequency, average_time_per_class, detail_of_all_data
from Tk_lib.commond_lib import TreeViewTable, random_beautiful_color


class DisplayMenu:
    def __init__(self, user="李振席"):
        self.root = tk.Tk()
        # 图形图表框
        self.__treeview_frame = ttk.Labelframe(self.root, width=800, text="详细信息")
        self.__pie_frame = ttk.Labelframe(self.root, text="饼状比例图")

        # top4
        self.__user = User.objects.get(user=user)
        self.__top_list_frame = ttk.Labelframe(self.root, text="使用排行")
        self.__top_list = Category.objects.filter(user=self.__user).order_by('-use_number')

        self.__menu_bar = tk.Menu(self.root)
        self.__display_model_menu = tk.Menu(self.__menu_bar, tearoff=0)
        self.__display_model_menu.add_command(label="展示统计图", command=self.__plot_detail_of_all_data)
        self.__menu_bar.add_cascade(label="图标", menu=self.__display_model_menu)
        self.root.config(menu=self.__menu_bar)

        self.__path = None
        self.table = None
        self.suptable = None
        self.__item_text = None

    def set_window(self):
        """ 对窗口的属性进行设置"""
        self.root.title("时间利用该分布")
        # windows下专用全屏
        self.root.state("zoomed")
        # 全屏无表头
        # root.attributes('-fullscreen', True)
        self.root.bind("<Escape>", lambda e: e.widget.quit())
        # self.root.iconbitmap("media/logo.ico")
        # root.overrideredirect(True)
        # root.configure(background = "burlywood2")

    def __plot_detail_of_all_data(self):
        f = plt.Figure(dpi=100)
        gs = GridSpec(3, 4, figure=f)
        plt.style.use('ggplot')
        plt.rcParams['font.sans-serif'] = ['SimHei']
        f.suptitle("详细信息分布")

        data = detail_of_all_data()
        color = random_beautiful_color()

        subfig1 = f.add_subplot(gs[1, :-1])
        subfig1.plot(data["every_day_of_month"][0], data["every_day_of_month"][1], label="every_day_of_month",
                     c=random.choice(color))
        subfig1.legend(loc='upper right')

        ax1 = f.add_subplot(gs[2, :])
        ax1.plot(data["every_week"][0], data["every_week"][1], label="every_week", c=random.choice(color))
        ax1.legend(loc="center right")

        ax2 = f.add_subplot(gs[0, -1:])
        ax2.plot(data["last_week_data"][0], data["last_week_data"][1], label="last_week_data", c=random.choice(color))
        ax2.plot(data["last_week_data"][0], [10.5]*len(data["last_week_data"][0]), c="red")
        ax2.legend(loc="center right")

        ax3 = f.add_subplot(gs[0, :-1])
        ax3.plot(data["last_month_data"][0], data["last_month_data"][1], label="last_month_data", c=random.choice(color))
        ax3.plot(data["last_month_data"][0], [10.5]*len(data["last_month_data"][0]), c="red")
        ax3.set_xticks(data["last_month_data"][0])
        ax3.legend(loc="center right")

        ax4 = f.add_subplot(gs[1, -1:])
        ax4.plot(data["every_month"][0], data["every_month"][1], label="every_month", c=random.choice(color))
        ax4.legend(loc="center right")

        root = tk.Tk()
        root.wm_state('zoomed')
        # root.attributes('-fullscreen', True)
        plot_pic = FigureCanvasTkAgg(f, root)
        plot_pic.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        toolbar = NavigationToolbar2Tk(plot_pic, root)
        toolbar.update()

    def set_table_bind_command(self, table):
        # for item in table.selection():
        #     self.__item_text = table.item(item, "value")
        pass
        # 提取文件路径的值

    def display_table(self):
        table_data = []
        train_modles = UseTime.objects.filter(user=self.__user).order_by('-start_time', '-use_time', 'category')

        # 获取表头，也就是model的verbose_name字段
        exclude_fields = ('id', 'user')  # 排除字段
        table_head = [f.verbose_name for f in UseTime._meta.fields if f.name not in exclude_fields]

        # 取数据
        for train_modle in train_modles:
            # 手动配
            row = [train_modle.category, train_modle.start_time, train_modle.stop_time, train_modle.use_time]
            table_data.append(row)

        self.__treeview_frame.pack(side=tk.LEFT, fill=tk.BOTH, padx=4, pady=4)
        self.__treeview_frame.propagate(0)  # 使组件大小不变，此时width才起作用
        self.suptable = TreeViewTable(self.__treeview_frame, table_head, table_data)
        self.table = self.suptable.get_table()
        self.table.bind('<<TreeviewSelect>>', lambda e: self.set_table_bind_command(self.table))
        self.suptable.tree_view_table_display()

    def display_pie(self):
        plot_images = self.__pie_frame
        plot_images.pack(side=tk.TOP, fill=tk.X)
        plt.style.use('ggplot')
        plt.rcParams['font.sans-serif'] = ['SimHei']

        # 设置图像大小
        f = plt.Figure()
        f.suptitle("TOP 6（次数）使用频率")
        color = ['tab:green', 'tab:red', '#0f0f0f80', 'tab:blue', 'tab:cyan', 'tab:orange']
        f.subplots_adjust(hspace=0)
        for i in self.__top_list[:2]:
            subfig1 = f.add_subplot(2, 1, 1)
            x, y = time_frequency(category=i.category)
            subfig1.plot(x, y, label=i.category, c=color[-1])
            subfig1.legend(loc='upper right')
            color.pop()

        for i in self.__top_list[2:6]:
            subfig2 = f.add_subplot(2, 1, 2)
            x, y = time_frequency(category=i.category)
            subfig2.plot(x, y, label=i.category, c=color[-1])
            subfig2.legend(loc='upper right')
            color.pop()

        plot_pic = FigureCanvasTkAgg(f, plot_images)
        plot_pic.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        # 导航条
        toolbar = NavigationToolbar2Tk(plot_pic, plot_images)
        toolbar.update()

    def display_info(self):
        self.__top_list_frame.pack(side=tk.TOP, fill=tk.BOTH)
        time = average_time_per_class()
        for i in time:
            ttk.Label(self.__top_list_frame, text=i+":"+str(time[i]['all_time'])+", "+str(time[i]["average_time"])).pack(side=tk.TOP)

    def display(self):
        self.set_window()
        self.display_table()
        self.display_pie()
        self.display_info()


if __name__ == '__main__':
    test = DisplayMenu()
    test.display()
    test.root.mainloop()
